<template>
  <div class="m-slide" @mouseenter="onStop" @mouseleave="onStart">
    <div
      :style="`will-change: transform; transform: translateX(${-left}px);`"
      class="u-slide-title"
      v-for="(item, index) in sliderData"
      :key="index"
      :title="item.title"
      @click="onClickTitle(item.title)"
    >
      {{ item.title }}
    </div>
  </div>
</template>
<script>
export default {
  name: "Slider",
  props: {
    sliderData: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      left: 0,
      moveTimer: null,
    };
  },
  created() {
    this.onStart();
  },
  methods: {
    onClickTitle(title) {
      // 通知父组件点击的标题
      this.$emit("getTitle", title);
    },
    onStop() {
      // 暂停滚动
      clearInterval(this.moveTimer);
    },
    onStart() {
      // 开始滚动
      if (this.sliderData.length > 4) {
        // 超过4条开始滚动
        this.getSlide();
      }
    },
    getSlide() {
      this.moveTimer = setInterval(() => {
        this.moveLeft();
      }, 5); // 1s移动200次
    },
    moveLeft() {
      if (this.left >= 320) {
        this.sliderData.push(this.sliderData.shift()); // 将第一条数据放到最后
        this.left = 0;
      } else {
        this.left += 0.2; // 每次移动0.2px
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.m-slide {
  width: 100%;
  margin: 60px auto;
  height: 45px;
  white-space: nowrap;
  overflow: hidden;
  .u-slide-title {
    display: inline-block;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    line-height: 45px;
    color: #1890ff;
    // width: 300px;
    // overflow: hidden;
    // text-overflow: ellipsis;
    // white-space: nowrap;
    cursor: pointer;
    &:hover {
      color: #1890ff;
    }
  }
}
</style>
